import React, { useState, useEffect } from 'react';
import ImageQuestion from './components/ImageQuestion';
import ChineseQuestion from './components/ChineseQuestion';
import GrammarQuestion from './components/GrammarQuestion';
import ScoreBoard from './components/ScoreBoard';
import ResultScreen from './components/ResultScreen';
import { imageQuestions, chineseQuestions } from './data/questions';
import { grammarQuestions } from './data/grammarQuestions';
import './App.css';

// 类型声明
// import type { GrammarQuestion as GrammarQ, ImageQuestionType, ChineseQuestionType } from './data/questions';

// 题目模式类型
// type Mode = 'image' | 'chinese' | 'grammar';

function App() {
  const [currentMode, setCurrentMode] = useState<'image' | 'chinese' | 'grammar' | null>(null);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [correctAnswers, setCorrectAnswers] = useState(0);
  const [wrongAnswers, setWrongAnswers] = useState<{question: string, userAnswer: string, correctAnswer: string}[]>([]);
  const [isCompleted, setIsCompleted] = useState(false);

  type Progress = {
    completed: number[];
    correct: number[];
    wrong: number[];
  };
  type UserProgress = {
    image: Progress;
    chinese: Progress;
    grammar: Progress;
  };
  const [userProgress, setUserProgress] = useState<UserProgress>({
    image: { completed: [], correct: [], wrong: [] },
    chinese: { completed: [], correct: [], wrong: [] },
    grammar: { completed: [], correct: [], wrong: [] }
  });

  useEffect(() => {
    const savedProgress = localStorage.getItem('japaneseLearningProgress');
    if (savedProgress) {
      setUserProgress(JSON.parse(savedProgress));
    }
  }, []);

  const saveProgress = (newProgress: any) => {
    setUserProgress(newProgress);
    localStorage.setItem('japaneseLearningProgress', JSON.stringify(newProgress));
  };

  const getFilteredQuestions = (mode: 'image' | 'chinese' | 'grammar') => {
    let allQuestions: any[] = [];
    switch (mode) {
      case 'image':
        allQuestions = imageQuestions;
        break;
      case 'chinese':
        allQuestions = chineseQuestions;
        break;
      case 'grammar':
        allQuestions = grammarQuestions;
        break;
      default:
        allQuestions = [];
    }
    const progress = userProgress[mode];
    return allQuestions.filter((question) => !progress.correct.includes(question.id));
  };

  const imageQuestionsData = getFilteredQuestions('image').slice(0, 5);
  const chineseQuestionsData = getFilteredQuestions('chinese').slice(0, 10);
  const grammarQuestionsData = getFilteredQuestions('grammar').slice(0, 8);

  const currentQuestions =
    currentMode === 'image' ? imageQuestionsData :
    currentMode === 'chinese' ? chineseQuestionsData :
    currentMode === 'grammar' ? grammarQuestionsData : [];
  const currentQuestion = currentQuestions[currentQuestionIndex];

  const handleAnswer = (isCorrect: boolean, userAnswer = '', usedHint = false) => {
    if (isCorrect) {
      setCorrectAnswers(prev => prev + 1);
      const newProgress = { ...userProgress };
      if (!usedHint) {
        newProgress[currentMode!].correct.push(currentQuestion.id);
      } else {
        newProgress[currentMode!].completed.push(currentQuestion.id);
      }
      saveProgress(newProgress);
    } else {
      const wrongAnswer = {
        question: currentMode === 'image'
          ? currentQuestion.sentence
          : currentMode === 'chinese'
          ? `中文：${currentQuestion.chinese}`
          : currentQuestion.question,
        userAnswer: userAnswer,
        correctAnswer: currentMode === 'grammar'
          ? currentQuestion.options.find((opt: any) => opt.isCorrect).text
          : currentQuestion.correctAnswers[0]
      };
      setWrongAnswers(prev => [...prev, wrongAnswer]);
      const newProgress = { ...userProgress };
      newProgress[currentMode!].wrong.push(currentQuestion.id);
      saveProgress(newProgress);
    }
  };

  const handleNext = () => {
    if (currentQuestionIndex < currentQuestions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
    } else {
      setIsCompleted(true);
    }
  };

  const handleRestart = () => {
    setCurrentQuestionIndex(0);
    setCorrectAnswers(0);
    setWrongAnswers([]);
    setIsCompleted(false);
    setCurrentMode(null);
  };

  const handleReviewWrong = () => {
    setCurrentQuestionIndex(0);
    setCorrectAnswers(0);
    setWrongAnswers([]);
    setIsCompleted(false);
  };

  const startMode = (mode: 'image' | 'chinese' | 'grammar') => {
    setCurrentMode(mode);
    setCurrentQuestionIndex(0);
    setCorrectAnswers(0);
    setWrongAnswers([]);
    setIsCompleted(false);
  };

  const handleBackToHome = () => {
    setCurrentMode(null);
    setCurrentQuestionIndex(0);
    setCorrectAnswers(0);
    setWrongAnswers([]);
    setIsCompleted(false);
  };

  const getProgressStats = (mode: 'image' | 'chinese' | 'grammar') => {
    const progress = userProgress[mode];
    let allQuestions: any[] = [];
    switch (mode) {
      case 'image':
        allQuestions = imageQuestions;
        break;
      case 'chinese':
        allQuestions = chineseQuestions;
        break;
      case 'grammar':
        allQuestions = grammarQuestions;
        break;
      default:
        allQuestions = [];
    }
    const totalCompleted = progress.correct.length + progress.completed.length;
    const accuracy = totalCompleted > 0 ? Math.round((progress.correct.length / totalCompleted) * 100) : 0;
    return {
      total: allQuestions.length,
      completed: totalCompleted,
      correct: progress.correct.length,
      accuracy: accuracy
    };
  };

  if (!currentMode) {
    const imageStats = getProgressStats('image');
    const chineseStats = getProgressStats('chinese');
    const grammarStats = getProgressStats('grammar');

    return (
      <div className="container">
        <div className="card">
          <h1 style={{ textAlign: 'center', marginBottom: '30px', color: '#333' }}>
            日语学习助手 🇯🇵
          </h1>
          <div style={{ textAlign: 'center', marginBottom: '40px' }}>
            <p style={{ fontSize: '18px', color: '#666', lineHeight: '1.6' }}>
              欢迎使用日语学习助手！选择您想要练习的模式开始学习吧！
            </p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', maxWidth: '500px', margin: '0 auto' }}>
            <div className="card" style={{ cursor: 'pointer', textAlign: 'center' }} onClick={() => startMode('image')}>
              <h3>📸 根据图片或语法填入日语</h3>
              <p style={{ color: '#666', marginTop: '10px' }}>
                通过图片或语法练习，提高词汇运用能力和语法结构掌握
              </p>
              <div style={{ marginTop: '15px', color: '#667eea', fontWeight: 'bold' }}>
                剩余 {imageQuestionsData.length} 题 / 总计 {imageStats.total} 题
              </div>
              {imageStats.completed > 0 && (
                <div style={{ marginTop: '10px', fontSize: '14px', color: '#28a745' }}>
                  已完成: {imageStats.completed} 题 | 正确率: {imageStats.accuracy}%
                </div>
              )}
            </div>
            <div className="card" style={{ cursor: 'pointer', textAlign: 'center' }} onClick={() => startMode('chinese')}>
              <h3>🔤 根据中文意思猜日语单词</h3>
              <p style={{ color: '#666', marginTop: '10px' }}>
                根据中文词语输入对应的日语单词，强化单词记忆
              </p>
              <div style={{ marginTop: '15px', color: '#667eea', fontWeight: 'bold' }}>
                剩余 {chineseQuestionsData.length} 题 / 总计 {chineseStats.total} 题
              </div>
              {chineseStats.completed > 0 && (
                <div style={{ marginTop: '10px', fontSize: '14px', color: '#28a745' }}>
                  已完成: {chineseStats.completed} 题 | 正确率: {chineseStats.accuracy}%
                </div>
              )}
            </div>
            <div className="card" style={{ cursor: 'pointer', textAlign: 'center' }} onClick={() => startMode('grammar')}>
              <h3>📚 N4-N2语法考察</h3>
              <p style={{ color: '#666', marginTop: '10px' }}>
                JLPT风格的语法选择题，提高语法理解能力
              </p>
              <div style={{ marginTop: '15px', color: '#667eea', fontWeight: 'bold' }}>
                剩余 {grammarQuestionsData.length} 题 / 总计 {grammarStats.total} 题
              </div>
              {grammarStats.completed > 0 && (
                <div style={{ marginTop: '10px', fontSize: '14px', color: '#28a745' }}>
                  已完成: {grammarStats.completed} 题 | 正确率: {grammarStats.accuracy}%
                </div>
              )}
            </div>
          </div>
          <div style={{ textAlign: 'center', marginTop: '40px', color: '#999', fontSize: '14px' }}>
            <p>💡 提示：系统会记住您的学习进度，已掌握的题目不会重复出现！</p>
          </div>
        </div>
      </div>
    );
  }

  if (isCompleted) {
    return (
      <div className="container">
        <ResultScreen
          correctAnswers={correctAnswers}
          totalQuestions={currentQuestions.length}
          wrongAnswers={wrongAnswers}
          onRestart={handleRestart}
          onReviewWrong={handleReviewWrong}
        />
      </div>
    );
  }

  return (
    <div className="container">
      {/* 返回首页按钮 */}
      <button className="back-home-btn" onClick={handleBackToHome}>
        🏠 返回首页
      </button>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '20px' }}>
        <div>
          {currentMode === 'image' ? (
            <ImageQuestion
              question={currentQuestion}
              onAnswer={handleAnswer}
              onNext={handleNext}
            />
          ) : currentMode === 'chinese' ? (
            <ChineseQuestion
              question={currentQuestion}
              onAnswer={handleAnswer}
              onNext={handleNext}
            />
          ) : currentMode === 'grammar' ? (
            <GrammarQuestion
              question={currentQuestion}
              onAnswer={handleAnswer}
              onNext={handleNext}
            />
          ) : null}
        </div>
        <div>
          <ScoreBoard
            correctAnswers={correctAnswers}
            totalQuestions={currentQuestions.length}
            currentQuestionIndex={currentQuestionIndex}
            wrongAnswers={wrongAnswers}
            userProgress={userProgress[currentMode!]}
          />
          <div className="card" style={{ marginTop: '20px' }}>
            <button className="btn" onClick={handleBackToHome} style={{ width: '100%' }}>
              返回主页
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;
